from django.shortcuts import render
from .models import Course
from django.http import Http404
from django.conf import settings
from utils import restful
import time
import os
import hmac
import hashlib


# 课程首页
def course_index(request):
    courses = Course.objects.all()
    context = {
        'courses': courses
    }
    return render(request, 'course/course_index.html', context=context)


# 课程详情页
def course_detail(request, course_id):
    try:
        course = Course.objects.get(pk=course_id)
        context = {
            'course': course
        }
        return render(request, 'course/course_detail.html', context=context)
    except:
        return Http404


# 获取课程视频的token
def course_token(request):
    # 获取视频文件完整链接
    file = request.GET.get('video')
    # 视频过期时间
    expiration_time = int(time.time()) + 2 * 60 * 60

    USER_ID = settings.BAIDU_CLOUD_USER_ID
    USER_KEY = settings.BAIDU_CLOUD_USER_KEY

    # 获取视频文件id
    extension = os.path.splitext(file)[1]
    media_id = file.split('/')[-1].replace(extension, '')

    key = USER_KEY.encode('utf-8')
    message = '/{0}/{1}'.format(media_id, expiration_time).encode('utf-8')
    signature = hmac.new(key, message, digestmod=hashlib.sha256).hexdigest()
    token = '{0}_{1}_{2}'.format(signature, USER_ID, expiration_time)
    return restful.result(data={'token': token})


# 课程订单页
def course_order(request, course_id):
    course = Course.objects.get(pk=course_id)
    context = {
        'course': course
    }
    return render(request, 'course/couese_order.html', context=context)
